<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\model\DeptModel;
use app\model\UserModel;

use app\Common;

class User{
    //常用数据表内容 及常用字典

    var $dept=[];
    var $group=[];
    var $sex=[1=>'男',2=>'女'];

    var $status=array('1'=>'在职','2'=>'离职','3'=>'黑名单');//员工状态
    var $status2=array('1'=>'正常','2'=>'停用'); //权限组的状态
    var $levels=array('1'=>'员工','2'=>'主管','3'=>'经理','4'=>'高级经理','5'=>'副总以上','99'=>'系统管理员');
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";

    public function __construct(){
        $list = Db::table("user")->select()->toArray();
        foreach($list as $k=>$v){
            $this->users[$v['id']]=$v;
        }
        Cache::set('users',$this->users);

        $dm=new DeptModel();
        $this->dept = $dm->getAll();

        $list = Db::table('user_group')->where('status',1)->select()->toArray();
        foreach($list as $k=>$v){
            $this->group[$v['id']]=$v;
        }        
    }

    //职员管理
    public function index(){
        $uid=Session::get('logonid');
        if(!$uid) header("location:/index.php/login");   
        $all=Request::param();

        $name_or_mobile=!empty($all['name_or_mobile'])?$all['name_or_mobile']:'';
        $dept_id = !empty($all['dept_id'])?$all['dept_id']:'';

        $me = Db::table('user')->find($uid);
        $chds = $this->getChildren($me['dept_id']);
        $depts =[$me['dept_id']];
        $depts =array_merge($depts,$chds);

        $list = Db::table("user");
        if($name_or_mobile){
            $list = $list->whereRaw("name='".$name_or_mobile."' or mobile='".$name_or_mobile."'");
        }
        if($dept_id){
            $list = $list->where('dept_id',$dept_id);
        }

        $list = $list->where('dept_id','in',implode(",",$depts));
        

        $list = $list->paginate(15)->toArray();

        foreach($list['data'] as &$kv){
            $kv['status_name'] = $this->status[$kv['status']];
            $kv['creater_name'] = $this->users[$kv['creater']]['name'];
            $kv['updater_name'] = $kv['updater']>1? $this->users[$kv['updater']]['name']:'';
            $kv['level_name'] = $this->levels[$kv['level']];
            $kv['dept_id_name'] = $this->dept[$kv['dept_id']]['name'];
            $kv['sex'] = $kv['sex']?$this->sex[$kv['sex']]:'';
            $kv['group_id_name'] = $this->group[$kv['group_id']]['name'];
            $kv['verify_str'] = $this->check_verify($kv);
        }

        //halt($list);
        $school = Db::table('dept')->where('type',2)->where('status',1)->select()->toArray();

        View::assign(['data'=>$list,'dept_id'=>$dept_id,'name_or_mobile'=>$name_or_mobile,'school'=>$school]);

        return View::fetch();
    }  

    private function check_verify($user){
        if(md5($user['password'].$user['create_time'])==$user['verify_code']) return '';
        return '密码异常！';
    }

    //对输入的参数做一些检测
    private function user_check(&$all=[]){

            //手机号码检测
            $mobile = Common::is_mobile($all['mobile']);

            if(!$mobile) {
                return ['code'=>0,'msg'=>'手机号码不正确！'];
            }


            $row=Db::table('user')->where('mobile',$all['mobile'])->where('id','<>',$all['id'])->value('name');
            if($row){
                return ['code'=>0,'msg'=>'手机号码与员工:['.$row.'] 重复!'];
            }

            //halt($_FILES);
            if($_FILES['file']['size']>0){
                $files =Common::upload();
                
                if($files['code']){
                    $all['image']=$files['msg'];
                    return ['code'=>1];
                }else{
                    return ["code"=>0,'msg'=>"<h1>".$files['msg']."</h1>"];
                }
            }
            return ['code'=>1];
    }

    //职员编辑方法
    public function edit(){

        $uid=Session::get('logonid');
        if(!$uid) header("location:/index.php/login");   

        $all = Request::param();
        $id=$all['id'];

        if($id<3) return "不能修改管理员资料！";

        if(empty($id)) return '无效的id!' ;
        $user = new UserModel();
        $me=$user->find($uid);

        //传入内容,保存数据并跳转
        if($id>0 && !empty($all['name'])){
            $check = $this->user_check($all); 
            if($check['code']<1){
                return $check['msg'].$this->back;
            }

            $all['update_time'] = date('Y-m-d H:i:s');
            $all['updater'] = $uid;

            Db::table('user')->save($all);
            header('location:/index.php/user');
        }
        //不传内容只有id,查出本条数据 并进入编辑
        $row = $user->find($id);
        $mydept=$this->my_depts($uid);

        View::assign([
            'dept'=>$mydept,
            'status'=>$this->status,
            'levels'=>$this->levels,
            'data'=>$row,
            'group'=>$this->group,
            'me'=>$me
        ]);

        return View::fetch('edit');
    }

    //分类新增
    public function user_add(){
        $uid=Session::get('logonid');
        if(!$uid) return header("location:/index.php/login");   

        $all = Request::param();
        if(!empty($all['name'])){
            if(!empty($all['id'])) return '无效的操作!';     
            if(!$all['uid']) return '无效的工号!';
            if(!$all['name']) return '无效的姓名!';

            $user = new UserModel();
            $row = $user::where('uid',$all['uid'])->find();
            if(!empty($row)) return '帐号已存在! ['. $all['uid']."]";

            $all['creater']  = Session::get('logonid');
            $all['password'] = md5("12345think");
            $all['create_time']  = date("Y-m-d H:i:s",time());
            $all['verify_code'] =md5($all['password'].$all['create_time']);

            $this->user_check($all);
            
            $res =$user->insert($all);
            return header("location:/index.php/user");
        }


        $mydept=$this->my_depts($uid);

        $user=Db::table('user')->find($uid);
        if($user['group_id']==1){
            $group=$this->group;
        }else{
            $group = Db::table('user_group')->where('name','like','驾校%')->select()->toArray();
        }
        halt($group);

        $arr = [
            'dept'=>$mydept,
            'status'=>$this->status,
            'levels'=>$this->levels,
            'group'=>$this->group
        ];
        //dump($arr);
        View::assign($arr);
        return View::fetch('user_add');
    }

    public function resetpwd($id){
        $uid=Session::get('logonid');
        if(!$uid) header("location:/index.php/login");   

        if(empty($id)) return 'error action!';
        $user = new UserModel();
        $ct=$user->where('id',$id)->value('create_time');

        $res = $user->update(['id'=>$id,'password'=>md5('12345think'),'verify_code'=>md5(md5('12345think').$ct)]);
        return "密码初始化：12345!".$this->back;
        //header("location:/index.php/user");
    }

    

    public function aboutme($value=''){
        $uid=Session::get('logonid');
        if(!$uid) header("location:/index.php/login");

        $all=Request::param(); 
        

        if(!empty($all['password'])) {
            $ct = Db::table('user')->where('id',$all['id'])->value('create_time');            
            if(!$all['password']) return json(['code'=>0,'msg'=>'Invalid password!']);
            $row=$all;
            $row['password']=md5($all['password'].'think');
            $row['verify_code'] =md5($row['password'].$ct);

            $res = Db::table('user')->save($row);
            return json(['code'=>$res,'msg'=>'修改完成!']);
        }


        $me = Db::table('user')->find($uid);
        View::assign(['data'=>$me]);
        return View::fetch('aboutme');
    }

    public function group_list(){
        $uid=Session::get('logonid');
        if(!$uid) header("location:/index.php/login/target/admin");
        
        $list = Db::table('user_group')->select()->toArray();
        foreach($list as &$kv){
            $kv['status_name'] = $this->status2[$kv['status']];
            $kv['creater_name'] = $this->users[$kv['creater']]['name'];
        }

        View::assign(['list'=>$list]);
        return View::fetch('user_group');
    }

    //组增改
    public function group_edit(){
        $uid=Session::get('logonid');
        if(!$uid) header("location:/index.php/login/target/admin");
        
        if($_POST){
            if(!trim($_POST['name'])) return json(['code'=>0,'msg'=>'无效名称！']);
            $all = Request::param();
            $all['name']=trim($all['name']);

            if(empty($_POST['id'])){
                $all['create_time'] = date('Y-m-d H:i:s');
                $all['creater'] = $uid;
                $all['status'] = 1;
            }
            $res = Db::table('user_group')->save($all);
            if($res){
                return json(['code'=>1,'msg'=>'成功！']);
            }else{
               return json(['code'=>0,'msg'=>'失败是成功他妈！']);
            }
        }

        View::assign(['list'=>$list]);
        return View::fetch('user_group');
    }

    public function getOne(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");  
        
        $all=Request::param();
        if(!empty($all['id'])){
            $row=Db::table('user')->find($all['id']);
            if($row){
                return json(['code'=>1,'data'=>$row,'msg'=>'找到资料,编号：'.$row['id']]);
            }else{
                return json(['code'=>0,'msg'=>'没找到任何信息.']);
            }
        }

        if(!empty($all['nameOrMobile'])){
            $nm = trim($all['nameOrMobile']); 
            $row = Db::query('select * from user where name=? or mobile=?',[$nm,$nm]);
            if(!count($row)) return json(['code'=>0,'msg'=>"职员【".$all['nameOrMobile']."】未曾找到!"]);

            $row[0]['level_name']=$this->levels[$row[0]['level']];
            return json(['code'=>1,'data'=>$row[0],'msg'=>'职员找到，姓名：'.$row[0]['name'].',编号：'.$row[0]['id']]);
        }

        return json(['code'=>0,'msg'=>'没找到任何信息！']);

    }    


    //我等部门
    public function my_depts($uid){
        $me = Db::table('user')->find($uid);
        $chds = $this->getChildren($me['dept_id']);
        $depts =[$me['dept_id']];
        $depts =array_merge($depts,$chds);

        $mydept =[];
        foreach($depts as &$d){
            $mydept[$d] = $this->dept[$d];
        }  

        return $mydept;      
    }

     //递归取得子类
    private function getChildren($id,&$arr=[]){
        foreach($this->dept as $d){
            if($d['fid']==$id){
                $arr[] = $d['id'];
                $this->getChildren($d['id'],$arr);
            }
        }
        return $arr;
    }    


}
